package com.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.model.UploadImage;
import com.service.ImageStoreService;
import com.util.DateUtil;


@Controller
@RequestMapping("/xheditor")
public class XheditorController {
	
	@Autowired
	private ImageStoreService imageStoreService;
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String image(
			HttpServletRequest request,
			HttpSession session,
			@RequestParam("filedata") MultipartFile file) throws Exception {

		// 将图片按日期分开存放，方便管理
		final String path_segment = "/upload/images/"
				+ DateUtil.getFormatedDate("yyyy/MM_dd");

		// 存放到web根目录下,如果日期目录不存在，则创建,
		// 注意 request.getRealPath("/") 已经标记为不推荐使用了.
		final String path = session.getServletContext().getRealPath("/") + path_segment;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 以下是真正的上传部分
		String error = "";
		// 取得原文件名
		String originName = file.getOriginalFilename();
	
		// 取得文件后缀
		String fileExt = originName.substring(originName.lastIndexOf(".") + 1);
		// 按时间戳生成图片文件名
		String picture = DateUtil.getFormatedDate("yyyyMMddHHmmss");
		
		String path_url = path_segment + "/" + picture;	//upload/images/2012/11_09/20121109223012.jpg
		UploadImage uploadImg = new UploadImage();
		uploadImg.setPath(path_url);
		uploadImg.setFormat(fileExt);
		uploadImg.setSize(file.getSize());
		BufferedImage src = ImageIO.read(file.getInputStream());
		uploadImg.setHeight(src.getHeight());
		uploadImg.setWidth(src.getWidth());
		uploadImg.setCreateAt(new Date());
		uploadImg.setImage(file.getBytes());
		
		imageStoreService.saveUploadImage(uploadImg);
//		try {
//
//			IOUtils.copy(file.getInputStream(), new FileOutputStream(new File(dir, picture)));
//
//		} catch (Exception e) {
//			System.out.println("error:"+e.getMessage());
//			error = e.getMessage();
//		}

		// 将图片路径按xheditor要求的json格式字符串返回
		
		//String url = path_segment + "/" + picture;	//upload/images/2012/11_09/20121109223012.jpg
		
		return "{\"err\":\"" + error + "\",\"msg\":\"" + path_url+ "."+ fileExt + "\"}";
	}
}
